<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="45%" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="100px" class="reply-form-custom">
        <el-form-item label="选择商品：" prop="productId">
          <div class="upLoadPicBox" @click="changeGood">
            <div v-if="formData.image" class="pictrue"><img :src="formData.image" style="width:60px;height:60px;"></div>
            <div v-else class="upLoad">
              <i class="el-icon-camera cameraIconfont"/>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="用户名称：" prop="nickname">
          <el-input v-model="formData.nickname" placeholder="请输入用户名称" />
        </el-form-item>
        <el-form-item label="评价文字：" prop="comment">
          <el-input v-model="formData.comment" type="textarea" :rows="4" placeholder="请输入评价内容" />
        </el-form-item>
        <el-form-item label="商品分数：" prop="productScore">
          <el-rate v-model="formData.productScore" :max="5" allow-half show-score />
        </el-form-item>
        <el-form-item label="服务分数：" prop="serviceScore">
          <el-rate v-model="formData.serviceScore" :max="5" allow-half show-score />
        </el-form-item>
        <el-form-item label="用户头像：" prop="avatar">
          <ImageUpload v-model="avatarList" :limit="1"/>
        </el-form-item>
        <el-form-item label="评价图片：" prop="pics">
          <ImageUpload v-model="picsList" :limit="5"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 商品选择弹窗 -->
    <ProductSelectDialog ref="productSelectDialog" @confirm="handleProductSelect" />
  </div>
</template>

<script>
  import * as ProductReplyApi from '@/api/store/reply';
  import ImageUpload from '@/components/ImageUpload';
  import ProductSelectDialog from '@/views/marketing/storeseckill/ProductSelectDialog.vue';
  export default {
    name: "ProductReplyForm",
    components: {
      ImageUpload,
      ProductSelectDialog
    },
    data() {
      return {
        // 弹出层标题
        dialogTitle: "",
        // 是否显示弹出层
        dialogVisible: false,
        // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
        formLoading: false,
        // 表单参数
        formData: {
          productId: undefined,
          image: '',
          productScore: undefined,
          serviceScore: undefined,
          comment: undefined,
          pics: '',
          nickname: undefined,
          avatar: '',
          deleted: 0, // 删除标记：0-未删除，1-已删除
        },
        avatarList: [],
        picsList: [],
        // 表单校验
        formRules: {
          productId: [{ required: true, message: '商品id不能为空', trigger: 'blur' }],
          productScore: [{ required: true, message: '商品分数不能为空', trigger: 'blur' }],
          serviceScore: [{ required: true, message: '服务分数不能为空', trigger: 'blur' }],
          comment: [{ required: true, message: '评论内容不能为空', trigger: 'blur' }],
          pics: [{ required: true, message: '评论图片不能为空', trigger: 'blur' }],
          nickname: [{ required: true, message: '用户名称不能为空', trigger: 'blur' }],
          avatar: [{ required: true, message: '用户头像不能为空', trigger: 'blur' }],
        },
      };
    },
    methods: {
      /** 打开弹窗 */
      async open(id) {
        this.dialogVisible = true;
        this.reset();
        // 修改时，设置数据
        if (id) {
          this.formLoading = true;
          try {
            const res = await ProductReplyApi.getProductReply(id);
            this.formData = res.data;
            // 确保 deleted 字段存在，如果后端没有返回则默认为 0
            if (this.formData.deleted === undefined) {
              this.formData.deleted = 0;
            }
            this.title = "修改评论";
            this.avatarList = this.formData.avatar
              ? this.formData.avatar.split(',').filter(Boolean)
              : [];
            this.picsList = this.formData.pics
              ? this.formData.pics.split(',').filter(Boolean)
              : [];
            // 商品图片回显
            if (this.formData.productId) {
              // 如果有商品图片API，可以在这里请求商品详情
              // 这里假设formData.image就是商品图片
              // 如果没有image字段，可以根据实际API获取
              // this.formData.image = await getProductImageById(this.formData.productId)
              // 否则保留原有image
            }
          } finally {
            this.formLoading = false;
          }
        } else {
          this.avatarList = [];
          this.picsList = [];
        }
        this.title = "新增评论";
      },
      /** 提交按钮 */
      async submitForm() {
        // 先同步图片字段
        this.formData.avatar = Array.isArray(this.avatarList) ? this.avatarList.join(',') : '';
        this.formData.pics = Array.isArray(this.picsList) ? this.picsList.join(',') : '';
        // 再校验
        await this.$refs["formRef"].validate();
        this.formLoading = true;
        try {
          const data = this.formData;
          // 修改的提交
          if (data.id) {
            await ProductReplyApi.updateProductReply(data);
            this.$modal.msgSuccess("修改成功");
            this.dialogVisible = false;
            this.$emit('success');
            return;
          }
          // 添加的提交
          await ProductReplyApi.createProductReply(data);
          this.$modal.msgSuccess("新增成功");
          this.dialogVisible = false;
          this.$emit('success');
        } finally {
          this.formLoading = false;
        }
      },
      /** 表单重置 */
      reset() {
        this.formData = {
          productId: undefined,
          image: '',
          productScore: undefined,
          serviceScore: undefined,
          comment: undefined,
          pics: '',
          nickname: undefined,
          avatar: '',
          deleted: 0, // 删除标记：0-未删除，1-已删除
        };
        this.resetForm("formRef");
      },
      changeGood() {
        this.$refs.productSelectDialog.open();
      },
      handleProductSelect(selectedProducts) {
        if (selectedProducts && selectedProducts.length > 0) {
          const product = selectedProducts[0];
          this.formData.productId = product.id;
          this.formData.image = product.image;
        }
      },
    }
  };
</script>

<style scoped>
.reply-form-custom .el-form-item {
  margin-bottom: 24px;
}
.reply-form-custom .el-input,
.reply-form-custom .el-textarea__inner {
  font-size: 15px;
}
.reply-form-custom .el-rate {
  font-size: 28px;
  vertical-align: middle;
}
.reply-form-custom .el-upload {
  margin-top: 0;
}
.pictrue {
  width: 60px;
  height: 60px;
  border: 1px dotted rgba(0,0,0,0.1);
  margin-right: 10px;
  position: relative;
  cursor: pointer;
}
.upLoad {
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px dotted rgba(0,0,0,0.1);
  cursor: pointer;
}
</style>
